import type { Word, Difficulty } from '@/types/vocabulary';

export const shuffleArray = <T>(array: T[]): T[] => {
  const newArray = [...array];
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  return newArray;
};

export const getWordCountByDifficulty = (difficulty: Difficulty): number => {
  switch (difficulty) {
    case 'easy':
      return 5;
    case 'medium':
      return 7;
    case 'hard':
      return 10;
    default:
      return 7;
  }
};

export const selectRandomWords = (words: Word[], count: number): Word[] => {
  const shuffled = shuffleArray(words);
  return shuffled.slice(0, Math.min(count, words.length));
};

export const generateWrongOptions = (
  correctAnswer: string,
  allWords: Word[],
  isEnglish: boolean,
  count: number = 3
): string[] => {
  const options = new Set<string>();
  const availableWords = allWords.filter(w => 
    isEnglish ? w.english !== correctAnswer : w.chinese !== correctAnswer
  );
  
  const shuffled = shuffleArray(availableWords);
  
  for (const word of shuffled) {
    if (options.size >= count) break;
    options.add(isEnglish ? word.english : word.chinese);
  }
  
  return Array.from(options);
};

export const calculateScore = (
  correctCount: number,
  totalCount: number,
  timeSpent?: number,
  maxTime?: number
): number => {
  const baseScore = (correctCount / totalCount) * 100;
  
  if (timeSpent && maxTime) {
    const timeBonus = Math.max(0, (1 - timeSpent / maxTime) * 20);
    return Math.round(baseScore + timeBonus);
  }
  
  return Math.round(baseScore);
};
